package com.example.myapplication.fragment

import android.os.Build
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.bumptech.glide.Glide
import com.drake.brv.utils.linear
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.example.myapplication.MainViewModel
import com.example.myapplication.R
import com.example.myapplication.databinding.CommentBinding
import com.example.myapplication.databinding.FragmentRewardBinding
import com.example.myapplication.db.Comment
import com.example.myapplication.db.Reward
import com.example.myapplication.db.ApplyUser
import com.example.myapplication.utils.TimeUtils
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class RewardFragment : BaseFragment<FragmentRewardBinding>() {
    private val mViewModel: MainViewModel by activityViewModels()
    lateinit var thisReward: Reward
    override fun initBinding(): FragmentRewardBinding {
        return FragmentRewardBinding.inflate(layoutInflater)
    }
    var rewardAccount=""
    var thisAccount=""
    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        val gson = Gson()
        val listType = object : TypeToken<List<Comment>>() {}.type
        val timeUtils=TimeUtils()
        mViewModel.Logged_user.observe(viewLifecycleOwner){
            thisAccount=it
        }
        mViewModel.thisRewardContext.observe(viewLifecycleOwner) {
            thisReward=it
            val timeUtil=TimeUtils()
            rewardAccount=thisReward.account
            mBinding.username.text="用户名 : "+thisReward.account
            mBinding.time.text="时间 : " + timeUtil.splitDateTime(thisReward.time)
            mBinding.price.text="价格: ￥" +thisReward.price
            mBinding.rewardContent.text="    "+thisReward.content
            mBinding.commentRecyclerView.models=gson.fromJson(thisReward.comment,listType)
            if(rewardAccount==thisAccount){
                mBinding.applyReward.visibility=View.GONE
            }else{
                mBinding.applyReward.visibility=View.VISIBLE
            }
            if (thisReward.rewardApplyAccountList != "") {
                val listType = object : TypeToken<List<ApplyUser>>() {}.type
                val applyUserList: List<ApplyUser> = gson.fromJson(thisReward.rewardApplyAccountList, listType)
                var thisUserApplyState: String? = null

                if (applyUserList != null) {
                    for (applyUser in applyUserList) {
                        if (applyUser.account == thisAccount) {
                            thisUserApplyState = when (applyUser.state) {
                                0 -> "已婉拒"
                                1 -> "正在申请"
                                2 -> "已同意，正在解决"
                                3 -> "已解决"
                                else -> ""
                            }
                            break
                        }
                    }

                    if (thisUserApplyState != null) {
                        mBinding.applyReward.text = thisUserApplyState
                        mBinding.applyReward.isEnabled = false
                    } else {
                        // 用户未申请，保持按钮可用并显示默认文本
                        mBinding.applyReward.text = "申请委托" // 或其他适当的文本
                        mBinding.applyReward.isEnabled = true
                    }
                } else {
                    // rewardApplyAccountList 为空，按钮保持可用
                    mBinding.applyReward.text = "申请委托" // 或其他适当的文本
                    mBinding.applyReward.isEnabled = true
                }
            }

        }

        mBinding.applyReward.setOnClickListener {
            Log.d("RewardFragment", "Apply button clicked by user: $thisAccount")
            mBinding.applyReward.text = "已申请"
            mBinding.applyReward.isEnabled = false

            val rewardUser = mViewModel.findUserByAccount(rewardAccount)
            if (rewardUser == null) {
                Log.e("RewardFragment", "Reward user not found for account: $rewardAccount")
                Toast.makeText(requireContext(), "用户不存在！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            Log.d("RewardFragment", "Found rewardUser: ${rewardUser.account}")

            val rewardType = object : TypeToken<List<Reward>>() {}.type
            val applyUserListType = object : TypeToken<List<ApplyUser>>() {}.type
            val rewardUserRewards: MutableList<Reward> = gson.fromJson(rewardUser.reward, rewardType)
            Log.d("RewardFragment", "Parsed rewardUserRewards: ${rewardUserRewards.size}")

            var rewardFound = false

            for (reward in rewardUserRewards) {
                if (reward == thisReward) { // 使用唯一标识符
                    rewardFound = true
                    val thisRewardApplyAccountList: MutableList<ApplyUser> = if (reward.rewardApplyAccountList.isEmpty()) {
                        mutableListOf()
                    } else {
                        gson.fromJson(reward.rewardApplyAccountList, applyUserListType)
                    }

                    // 检查用户是否已经申请，避免重复添加
                    if (!thisRewardApplyAccountList.any { it.account == thisAccount }) {
                        thisRewardApplyAccountList.add(ApplyUser(thisAccount, 1))
                        Log.d("RewardFragment", "Added ApplyUser: $thisAccount with state 1")
                    } else {
                        Log.d("RewardFragment", "User $thisAccount has already applied for Reward ${reward.account}")
                    }

                    // 更新 rewardApplyAccountList
                    reward.rewardApplyAccountList = gson.toJson(thisRewardApplyAccountList)
                    Log.d("RewardFragment", "Updated rewardApplyAccountList: ${reward.rewardApplyAccountList}")

                    break // 找到后退出循环
                }
            }

            if (!rewardFound) {
                Log.e("RewardFragment", "No matching Reward found with id: ${thisReward.account}")
                Toast.makeText(requireContext(), "奖励不存在！", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 更新 rewardUser.reward
            rewardUser.reward = gson.toJson(rewardUserRewards, rewardType)
            Log.d("RewardFragment", "Serialized rewardUser.reward: ${rewardUser.reward}")

            // 更新数据库
            lifecycleScope.launch(Dispatchers.IO) {
                mViewModel.updateUser(rewardUser)
                Log.d("RewardFragment", "Updated user: ${rewardUser.account}")
            }

            Toast.makeText(requireContext(), "申请成功！", Toast.LENGTH_SHORT).show()
        }

        mBinding.comeBack.setOnClickListener {
            findNavController().popBackStack()
        }
        mBinding.toComment.setOnClickListener {
            showBottomSheetDialog(false)
        }
        mBinding.commentRecyclerView.linear().setup{
            addType<Comment>(R.layout.comment)
            onBind {
                val binding = getBinding<CommentBinding>()
                val model = getModel<Comment>()
                Glide.with(context)
                    .load(R.drawable.user)
                    .into(binding.userImage)
                binding.account.text = model.account
                binding.comment.text = model.commentContent
                binding.time.text=timeUtils.splitDateTime(model.time)
                itemView.setOnClickListener {

                }
            }
        }

    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun showBottomSheetDialog(isToRewardButNotToComment:Boolean) {
        val gson = Gson()
        // 创建 BottomSheetDialog 对象
        val bottomSheetDialog = BottomSheetDialog(requireContext())

        // 使用布局 inflater 加载自定义的底部弹出框布局
        val view = layoutInflater.inflate(R.layout.bottom_sheet_comment, null)

        // 获取布局中的控件
        val etComment = view.findViewById<EditText>(R.id.et_comment)
        val btnSubmitComment = view.findViewById<Button>(R.id.btn_submit_comment)

        // 设置按钮点击事件，处理评论提交
        btnSubmitComment.setOnClickListener {
            val commentText = etComment.text.toString().trim()

            if (commentText.isNotEmpty()) {
                // 在这里处理评论逻辑，比如发送评论到服务器或添加到 RecyclerView
                Toast.makeText(requireContext(), "评论提交成功", Toast.LENGTH_SHORT).show()
                val timeTool=TimeUtils()
                if(isToRewardButNotToComment){

                }else{
                    val listType = object : TypeToken<List<Comment>>() {}.type
                    val rewardType = object : TypeToken<List<Reward>>() {}.type
                    val user=mViewModel.findUserByAccount(rewardAccount)
                    if(user!=null){
                        var comments= mutableListOf<Comment>()
                        val rewards:MutableList<Reward> =gson.fromJson(user.reward  ,rewardType)
                        rewards.forEach{
                            if(it==thisReward){
                                    if(thisReward.comment!=""){
                                        comments =gson.fromJson(thisReward.comment,listType)
                                        comments.add(Comment(isToRewardButNotToComment,thisAccount,etComment.text.toString(),timeTool.thisTime()))
                                    }else{
                                        comments.add(Comment(isToRewardButNotToComment,thisAccount,etComment.text.toString(),timeTool.thisTime()))
                                    }
                                    it.comment = gson.toJson(comments)
                                    mViewModel.updateUser(user)
                                    thisReward.comment=gson.toJson(comments)
                                return@forEach
                            }
                        }
                        user.reward=gson.toJson(rewards,rewardType)
                        mBinding.commentRecyclerView.models=comments
                        lifecycleScope.launch (Dispatchers.IO){
                            mViewModel.updateUser(user)
                        }
                    }

                }
                bottomSheetDialog.dismiss()
            } else {
                Toast.makeText(requireContext(), "请输入评论", Toast.LENGTH_SHORT).show()
            }
        }

        // 设置 BottomSheetDialog 的视图
        bottomSheetDialog.setContentView(view)

        // 显示 BottomSheetDialog
        bottomSheetDialog.show()
    }
}